#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#include "bzrc.h"

#define IP_ADDRESS "127.0.0.1"
extern int debug;
int running;

typedef struct {
	FILE* fSocket;
	int tankID;
} param;

void *beStupid(void* args);
void *shootStupid(void* args);
void intHandler();

int main(int argc, char* argv[]) {
	int tcpSocket = 0;
	FILE* fSocket = 0;
	pthread_t* threads;
	param* threadArgs;
	int threadCount;
	int i;
	running = 1;
	signal(SIGINT, intHandler);
	signal(SIGKILL, intHandler);
	if (argc < 3) {
		fprintf(stderr, "usage: dumb_agent numagents port [debug 1:0]\n");
		exit(-1);
	}
	if (argc == 4 && atoi(argv[3]) == 1) {
		debug = 1;
	}

	threadCount = atoi(argv[1]);
	threads = (pthread_t*)malloc(sizeof(pthread_t) * threadCount);
	threadArgs = (param*)malloc(sizeof(param) * threadCount);
	BZRCConnect(IP_ADDRESS, atoi(argv[2]), &tcpSocket, &fSocket);
	for (i = 0; i < threadCount; i++) {
		threadArgs[i].fSocket = fSocket;
		threadArgs[i].tankID = i;
		pthread_create(&threads[i], NULL, beStupid, (void*)&threadArgs[i]);
	}
	for (i = 0; i < threadCount; i++) {
		pthread_join(threads[i], NULL);
	}
	BZRCDisconnect(tcpSocket, fSocket);
	free(threadArgs);
	free(threads);
	printf("Agents shut down\n");
	return 0;
}

void *beStupid(void* args) {
	param* params = (param*)args;
	FILE* fSocket = params->fSocket;
	int tankID = params->tankID;
	int sleeptime;
	pthread_t gunnerThread;
	pthread_create(&gunnerThread, NULL, shootStupid, args);
	//printf("Tank %d reporting in\n", tankID);
	while (running) {
		setSpeed(fSocket, tankID, 1);
		sleeptime = (rand() % 5000000) + 3000000;
		//printf("tank %d sleeping for %f seconds\n", tankID, (float)sleeptime/(float)1000000);
		usleep(sleeptime);
		setAngVel(fSocket, tankID, 0.5);
		sleeptime = 2000000;
		usleep(sleeptime);
		setAngVel(fSocket, tankID, 0);
	}
	setSpeed(fSocket, tankID, 0);
	pthread_join(gunnerThread, NULL);
	return 0;
}

void *shootStupid(void* args) {
	param* params = (param*)args;
	FILE* fSocket = params->fSocket;
	int tankID = params->tankID;
	int sleeptime;
	while (running) {
		//shoot(fSocket, tankID);
		sleeptime = (rand() % 1000000) + 1500000;
		usleep(sleeptime);
	}
	return 0;
}

void intHandler() {
	printf("Shutting down agents...\n");
	running = 0;
	return;
}


